package com.pig4cloud.pig.demo.Service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pig4cloud.pig.demo.Mapper.CarouselMapper;
import com.pig4cloud.pig.demo.Service.CarouselService;
import com.pig4cloud.pig.demo.feign.Entity.Carousel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class CarouselServiceImpl implements CarouselService {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private CarouselMapper carouselMapper;
    //该方法的作用是将redis中的carousel的图片获取到前端
    public List<String> getCarouselList(){
        List<String> list = (List<String>)redisTemplate.opsForValue().get("list");
        return list;
    }

    //设置redis中的图片数据
    public void setCarouselList(List<String> list){
        redisTemplate.opsForValue().set("list",list);
    }


    //定时从mysql取数据到redis中
    @Scheduled(cron = "0 */3 * * * ?")
//    @Scheduled(cron = "*/5 * * * * ?")
    public void findCarouselList(){
        System.out.println("我是定时器");
        List<String> imgList=new ArrayList<>();
        QueryWrapper<Carousel> wrapper = new QueryWrapper<>();
        wrapper.like("status",1);
        wrapper.orderByDesc("created_time");
        wrapper.last("limit 4");
        List<Carousel> list = carouselMapper.selectList(wrapper);
        for(Carousel carousels:list){
            imgList.add(carousels.getImg());
        }
        System.out.println(imgList);
        setCarouselList(imgList);
    }

    //添加轮播图数据
    public void saveCarousel(String img){
        Carousel carousel=new Carousel();
        carousel.setImg(img);
        int i=carouselMapper.insert(carousel);
        if(i==1){
            System.out.println("添加成功");
        }else{
            System.out.println("添加失败");
        }


    }
}
